package com.gxuwz.Market.business.action.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.gxuwz.Market.business.entity.ServiceField;
import com.gxuwz.Market.business.entity.ServiceForm;
import com.gxuwz.Market.business.entity.ServiceTask;
import com.gxuwz.Market.business.entity.TemplateUpload;
import com.gxuwz.Market.business.service.IServiceDataService;
import com.gxuwz.Market.business.service.IServiceFormService;
import com.gxuwz.Market.business.service.IServiceTaskService;
import com.gxuwz.core.pagination.Result;
import com.gxuwz.core.util.UidUtils;
import com.gxuwz.core.web.action.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

import util.FieldUtil;

public class ServiceFormAction extends BaseAction implements Preparable, ModelDriven<ServiceForm> {

	protected static final String LIST_JSP = "/WEB-INF/page/web/ServiceForm_list.jsp";  
	protected static final String ADD_JSP = "/WEB-INF/page/web/ServiceForm_add.jsp";
	protected static final String TPL_JSP = "/WEB-INF/page/web/ServiceForm_tpl.jsp";	//作为模板页面
	protected static final String EDIT_JSP = "/WEB-INF/page/web/ServiceForm_edit.jsp";
	protected static final String TASK_EDIT_FORM_JSP = "/WEB-INF/page/web/ServiceTask_edit_form.jsp";
	protected static final String DETAILS_JSP = "/WEB-INF/page/web/ServiceForm_details.jsp";
	protected static final String  UPLOAD_File = "/WEB-INF/page/web/uploadFile.jsp";
	@Autowired
	private IServiceFormService serviceFormService;
	@Autowired
	private IServiceDataService serviceDataService;
	@Autowired
	private IServiceTaskService serviceTaskService;
	
	private ServiceForm serviceForm;
	private ServiceTask serviceTask;
	private Result<ServiceForm> pageResult;
	
	private List<ServiceField> fieldList;
	private  Integer fileId;//文件的Id
	private String fileName;//文件的名字
	private String fileContent;//文件类型
	private String fieldValue;
	public TemplateUpload  temp;
	
	
	
	
	
	
	
	@Override
	public void prepare() throws Exception {
		if(null == serviceForm){
			serviceForm = new ServiceForm();
			if(null==temp)
			{
				temp=new TemplateUpload();
			}
		}
		if(null == serviceTask){
			serviceTask = new ServiceTask();
		}
	}

	@Override
	public ServiceForm getModel() {
		return serviceForm;
	}
	
	@Override
	public String execute() throws Exception {
		
		return SUCCESS;
	}
	
	/**
	 * 复制任务
	 * @return
	 */
	public String toCopy(){
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		String oldName = serviceTask.getDataName();
		serviceTask.setId(null);
		serviceTask.setTaskId(UidUtils.MINIUID());
		String newName = "service_"+serviceTask.getTaskId()+"_data";
		serviceTask.setDataName(newName);
		serviceTask.setTaskName(serviceTask.getTaskName()+"-拷贝");
		serviceTask.setTaskState(1);
		serviceTask.setTaskType(1);
		serviceTaskService.add(serviceTask);
		serviceDataService.copy(newName, oldName);
		serviceTask = serviceTaskService.findByProperty("dataName", newName).get(0);
		return toEditTaskForm();
	}
	
	/**
	 * 修改已有任务的表格格式（跳转页面）
	 * @return
	 */
	public String toEditTaskForm(){
		serviceTask = serviceTaskService.findById(serviceTask.getId());
		serviceForm = serviceFormService.findByProperty("formId", serviceTask.getFormId()).get(0);
		fieldList = FieldUtil.fieldOfForm(serviceForm);
		setForwardView(TASK_EDIT_FORM_JSP);
		return SUCCESS;
	}
	
	/**
	 * 修改已有任务的表格格式
	 * @return
	 */
	public String editTaskForm(){

		ServiceForm form = serviceFormService.findByProperty("formId", serviceForm.getFormId()).get(0);
		serviceTask = serviceTaskService.findByProperty("taskId", serviceTask.getTaskId()).get(0);
		List<ServiceField> fieldOld = FieldUtil.fieldOfForm(form);
		List<ServiceField> fieldNew = FieldUtil.fieldOfFormNo(serviceForm);
		int i = 0;
		for(String fValue:fieldValue.split(",")){
			fieldNew.get(i).setValue(fValue);
			i++;
		}
		try{
			serviceDataService.editTaskForm(fieldOld, fieldNew, serviceTask.getDataName());
		}catch(Exception e){
			System.out.println(e);
		}
		
		/*
		//修改格式
		form.setFieldLen(serviceForm.getFieldLen());
		form.setFieldNames(serviceForm.getFieldNames());
		form.setFieldType(serviceForm.getFieldType());
		form.setFieldNum(serviceForm.getFieldNum());
		form.setFormName(serviceForm.getFormName());
		form.setRemark(serviceForm.getRemark());
		serviceFormService.update(form);
		*/
		String createrId = (String)getRequest().getSession().getAttribute("userId");
		serviceForm.setFormId(UidUtils.UID());
		serviceForm.setCreateTime(new Timestamp(new Date().getTime()));
		serviceForm.setCreaterId(createrId);
		serviceForm.setIsDelete(1);
		serviceFormService.add(serviceForm);
		
		serviceTask.setFormId(serviceForm.getFormId());
		serviceTaskService.update(serviceTask);
		
		serviceForm = new ServiceForm();
		return openList();
	}
	
	/**
	 * 打开列表页面
	 * @return
	 */
	public String openList(){
		pageResult = serviceFormService.find(serviceForm, getPage(), getRow());
		setForwardView(LIST_JSP);
		return SUCCESS;
	}


	/**
	 * 打开修改页面
	 * @return
	 */
	public String openEdit(){
		serviceForm = serviceFormService.findById(serviceForm.getId());
		fieldList = FieldUtil.fieldOfForm(serviceForm);
		setForwardView(EDIT_JSP);
		return SUCCESS;
	}
	
	public String edit(){
		ServiceForm sf = serviceFormService.findById(serviceForm.getId());

		if(sf.getFormState() == 1){
			sf.setIsDelete(1);
			serviceFormService.update(sf);
			
//			sf.setId(null);
//			sf.setFormId(UidUtils.UID());
//			sf.setFormState(0);
			serviceForm.setId(null);
			serviceForm.setFormId(UidUtils.UID());
			serviceForm.setFormState(0);
			serviceForm.setIsDelete(0);
			serviceForm.setCreaterId(sf.getCreaterId());
			serviceForm.setCreateTime(sf.getCreateTime());
			
			serviceFormService.add(serviceForm);
		}else{
			sf.setFieldLen(serviceForm.getFieldLen());
			sf.setFieldNames(serviceForm.getFieldNames());
			sf.setFieldType(serviceForm.getFieldType());
			sf.setFieldNum(serviceForm.getFieldNum());
			sf.setFormName(serviceForm.getFormName());
			sf.setRemark(serviceForm.getRemark());
			serviceFormService.update(sf);
		}
		
		

		

		serviceForm = new ServiceForm();
		return openList();
	}
	
	/**
	 * 表格详情
	 * @return
	 */
	public String openDetails(){
		serviceForm = serviceFormService.findById(serviceForm.getId());
		fieldList = FieldUtil.fieldOfForm(serviceForm);
		setForwardView(DETAILS_JSP);
		return SUCCESS;
	}
	/**
	 * 作为模板
	 * @return
	 */
	public String asTpl() {
		serviceForm = serviceFormService.findById(serviceForm.getId());
		fieldList = FieldUtil.fieldOfForm(serviceForm);
		setForwardView(TPL_JSP);
		return SUCCESS;
	}
	
	
	
	/**
	 * 文件的下载
	 * @return
	 * @author 黄森南
	 * @throws Exception 
	 * @date 2018.01.27
	 */
	
	public void getInputStream() throws Exception
	{
	temp=serviceFormService.findByFid(fileId);
	fileContent=temp.getFileContentType();
 	fileName=temp.getFileFileName();
		InputStream is = new FileInputStream(temp.getFilePath());
         //下载到哪里？客户端
         HttpServletResponse response = ServletActionContext.getResponse();
         response.addHeader("content-disposition", "attachment;filename="+java.net.URLEncoder.encode(fileName,"utf-8"));
          OutputStream os =response.getOutputStream();
        //弹出下载的框filename:提示用户下载的文件名
         byte[] b = new byte[1024];
         int size = is.read(b);
         while(size>0){
             os.write(b,0,size);
            size = is.read(b);
        }
    is.close();
    os.close();
	}
	
	public String openAdd() {
		setForwardView(ADD_JSP);
		return SUCCESS;
	}
	/**
	 * 删除
	 * @return
	 */
	public String delete() {
		serviceFormService.delete(serviceForm.getId());
		serviceForm = new ServiceForm();
		return openList();
	}
	
	public String add() {
		String createrId = (String)getRequest().getSession().getAttribute("userId");
		
		serviceForm.setFormId(UidUtils.UID());
		serviceForm.setCreateTime(new Timestamp(new Date().getTime()));
		serviceForm.setCreaterId(createrId);
		serviceForm.setFormState(0);
		serviceForm.setIsDelete(0);
		serviceFormService.add(serviceForm);
		//重置表格信息
		serviceForm = new ServiceForm();
		return openList();
	}
	

	public ServiceForm getServiceForm() {
		return serviceForm;
	}

	public void setServiceForm(ServiceForm serviceForm) {
		this.serviceForm = serviceForm;
	}

	public Result<ServiceForm> getPageResult() {
		return pageResult;
	}

	public void setPageResult(Result<ServiceForm> pageResult) {
		this.pageResult = pageResult;
	}

	public List<ServiceField> getFieldList() {
		return fieldList;
	}

	public void setFieldList(List<ServiceField> fieldList) {
		this.fieldList = fieldList;
	}

	public Integer getFileId() {
		return fileId;
	}

	public void setFileId(Integer fileId) {
		this.fileId = fileId;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFileContent() {
		return fileContent;
	}

	public void setFileContent(String fileContent) {
		this.fileContent = fileContent;
	}

	public ServiceTask getServiceTask() {
		return serviceTask;
	}

	public void setServiceTask(ServiceTask serviceTask) {
		this.serviceTask = serviceTask;
	}

	public String getFieldValue() {
		return fieldValue;
	}

	public void setFieldValue(String fieldValue) {
		this.fieldValue = fieldValue;
	}

	








	
	
	
}
